var datagrid; //定义全局变量datagrid（表格编辑）
var editRow = undefined; //定义全局变量：当前编辑的行
var selectUserId = "";//人员编辑id
var methodTypeData;//识别评价方法
//风险评价明细表options
var tableOptions = {
    url:ROOT_PATH+'/risk/recognise/queryRecogniseDetailListByDetailId.shtml',
    queryParams: {
        businessId:recogniseDetailId
        //action: 'query'
    }, //查询参数
    iconCls: 'icon-save', //图标
    //pagination: true, //显示分页
    //pageSize: 3, //页大小
    //pageList: [3, 6, 9], //页大小下拉选项此项各value是pageSize的倍数
    rownumbers:true,
    singleSelect:true,
    fit: true, //datagrid自适应宽度
    fitColumns: true, //列自适应宽度
    striped: true, //行背景交换
    nowap: true, //列内容多时自动折至第二行
    //border: false,
    toolbar:'#tb',
    idField: 'id', //主键
    columns:[]
    /* onClickCell:function(index, field, value){
     //alert(field);
     datagrid.datagrid("beginEdit", 0);
     var ed = $(this).datagrid('getEditor', {index:index,field:field});
     $(ed.target).focus();
     },*/
   /* onAfterEdit: function (rowIndex, rowData, changes) {
        //endEdit该方法触发此事件
        // var rows= datagrid.datagrid("getChanges");
        editRow = undefined;
    },
    onDblClickRow: function (rowIndex, rowData) {
        //双击开启编辑行
        editTableRow();
        /!*if (editRow != undefined) {
         datagrid.datagrid("endEdit", editRow);
         }
         if (editRow == undefined) {
         datagrid.datagrid("beginEdit", rowIndex);
         editRow = rowIndex;
         }*!/
    }*/
};

$(function(){
    //加载部门下拉列表
    queryDepartmentTree();
    //加载风险区域
    queryRegionList();
    //加载数据字典
    queryMethodTypeList("methodTypeId",CONSTANT.DictionaryTypeDefConstants.RISK_RECOGNISE_MOTHOD);//评价方法
    //加载数据字典
    queryDictionaryList("jobTypeId",CONSTANT.DictionaryTypeDefConstants.JOBTYPE);//作业类型
    //对象类型
    changeType();
    /**
     * 保存按钮事件
     */
    $('#btn_save').on("click", function () {
        //var ret = $("#detail").form('validate');
        var formIds = "";
        if(valideForm()){
            layer.confirm("确定保存？",{btn:['确定','取消']},function(){
                var layerIndex=parent.layer.getFrameIndex(window.name); //获取窗口索引
                //序列化表单数据
                var data = $("#seriousForm").serializeArray();
                $.ajax({
                    url:ROOT_PATH + '/risk/serious/addSeriousInfo.shtml',//提交地址
                    data:data,//将表单数据序列化
                    type:"POST",
                    dataType:"json",
                    success:function(result){
                        if (result.success){
                            layer.msg(result.message,{time:1000,icon:1},function(){
                                WindowManager.closeLayer({
                                    returnValue:""
                                });
                            });
                        }else{

                            layer.msg(result.message,{time:1000,icon:1},function(){
                                //parent.layer.close(layerIndex);
                            });
                        }
                    }
                });
            });
        }else{
            layer.msg("请按规则填写信息!",{time:1000,icon:2});
        }
        //验证表单
        function valideForm() {
            //alert($("#detailForm").form('validate'));
            if(recogniseType==0){
                return $("#recogniseForm1").form('validate')&&$("#recogniseForm2").form('validate')&&$("#recogniseForm3").form('validate')&&
                    $("#equipment").form('validate')&&$("#detailForm").form('validate');
            }else{
                return $("#recogniseForm1").form('validate')&&$("#recogniseForm2").form('validate')&&$("#recogniseForm3").form('validate')&&
                    $("#job1").form('validate')&&$("#job2").form('validate')&&$("#detailForm").form('validate');
            }
        }

    });
    /**
     * 绑定风险识别对象类型切换下拉列表
     */
    $("#recogniseType").combobox({
        onChange:function(newVal,oldVal){
            //var type = $("#recogniseType").val();
            recogniseType = newVal;
            changeType();
        }
    });
    /**
     * 绑定人员选择事件
     */
    $("#recogniseUsers").tagbox({
        iconWidth: 15,
        height: 30
       /* ,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                selectUserId ="recogniseUsers";
                add_contractorInfo_func();
            }
        }]*/
    });
    /**
     * 绑定作业项目选择事件
     */
    $("#jobProject").textbox({
        iconWidth: 15,
        height: 30
        /*,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                //selectUserId ="recogniseUsers";
                add_jobProject_func();
            }
        }]*/
    });
    /**
     * 绑定风险度选择事件
     */
    $("#riskGrade").textbox({
        iconWidth: 15,
        height: 30,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                WindowManager.openLayer({
                    type: 2,
                    title: '选择风险矩阵信息',
                    area: ['60%', '70%'],
                    content: ROOT_PATH + '/risk/matrix/toMatrixPage.shtml',
                    callBack:function(data){//窗口关闭后的回调函数
                       /* var riskGradeED= datagrid.datagrid('getEditor', {index:editRow,field:'riskGrade'});
                        var riskGradeIdED= datagrid.datagrid('getEditor', {index:editRow,field:'riskGradeId'});
                        $(riskGradeED.target).textbox("setValue",data.riskMax)*/
                        //$(riskGradeIdED.target).textbox("setValue",data.id)
                        var riskGrade = data.riskMax;
                        var resultGrade = riskGrade.substring(0,1);
                        var possibilityGrade = riskGrade.substring(1,2);
                        $("#resultGrade").textbox("setValue",resultGrade);
                        $("#possibilityGrade").textbox("setValue",possibilityGrade);
                        $("#riskGrade").textbox("setValue",riskGrade);


                    }
                });
            }
        }]
    });
    /**
     * 初始化评价人员数据
     */
    //设置data
    var userIdsArr = recogniseUserIds.split(',');
    var userNamesArr = recogniseUserNames.split(',')
    var userData = [];
    for(i=0;i<userIdsArr.length;i++){
        userData.push({id:userIdsArr[i],realName:userNamesArr[i]})
    }
    //var userData = [{id:loginUserId,realName:loginUserRealName}];
    $('#recogniseUsers').tagbox({
        data:userData,
        valueField:'id',
        textField:'realName',
        onBeforeRemoveTag:function(value){
            //alert(value);
            var val = $('#recogniseUsers').tagbox("getValues");
            if(val.length<=1){
                return false;
            }
        }
    });
    //选中所有的data
    for(i=0;i<userData.length;i++){
        $('#recogniseUsers').tagbox("select",userData[i].id);
    }

});

/**
 * 定义表单验证
 */
$.extend($.fn.validatebox.defaults.rules, {
    integer: {// 验证非负整数
        validator: function (value) {
            //return /^[+]?[1-9]+\d*$/i.test(value);
            return  /^\d+$/.test(value);
        },
        message: '请输入整数'
    },
    validSelect:{//验证为空字符串
        validator:function(value){
            //alert(value!="请选择");
            return value!="请选择"&&value!='';
        },
        message:'请选择'
    },
    validRegionSelect:{//验证风险区域
        validator:function(value,param){
            var val = $(param[0]).val();
            //alert(value!="请选择");
            return val!='';
        },
        message:'请选择'
    },
    validRecogniseUsers:{//验证风险评估人员
        validator:function(value,param){
            //console.log(value);
            return value!='';
        }
    }

});
/**
 * 切换对象类型的方法
 */
function changeType(){
    if(recogniseType==1){
        $('.equipment').hide();
        //$("#equipment").form('clear');
        //$('.equipmentInput').textbox("disableValidation");
        $('.job').show();
        //$('.jobInput').textbox("enableValidation");
    }else{
        $('.job').hide();
        //$("#job1").form('clear');
        //$("#job2").form('clear');
        // $('.jobInput').textbox("disableValidation");
        $('.equipment').show();
        //$('.equipmentInput').textbox("enableValidation");
    }
    //加载数据字典
    queryMethodTypeList("methodTypeId",CONSTANT.DictionaryTypeDefConstants.RISK_RECOGNISE_MOTHOD);//评价方法
}
/**
 * 定义不同方法的编辑表格字段
 */
var base_Field = [{field:'danger',title:'危害',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }},
    {field:'consequence',title:'主要后果',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }},
    {field:'riskTypeName',width:100,hidden:true,editor:{type:'textbox'}},
    {field:'riskTypeId',title:'风险类别',width:300,
        formatter:function(value,row,index){
            if(row.riskTypeName){
                return row.riskTypeName;
            }
            return '';
        },
        editor:{type:'combotree',
            options:{
                required:'true'
            }
        }
    },
    {field:'riskGrade',title:'风险等级',width:150, editor:{type:'textbox',
        options:{
            required:true,
            editable:false,
            icons: [{
                iconCls:'icon-add',
                handler: function(e){
                    add_riskLevelInfo_func();
                }
            }]

        }
    }},
    {field:'existMeasure',title:'现有控制措施及执行情况',width:350, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }},
    {field:'adviseMeasure',title:'建议控制措施',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }}
];
var scl_Field = [
    /*{field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'checkProject',title:'检查项目',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }},
    {field:'checkStandard',title:'检查标准',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }}
];
var pha_Field = [
   /* {field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'event',title:'事件',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }}];
var fmea_Field = [
    /*{field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'analyzeProject',title:'分析项目',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }},
    {field:'failureMode',title:'失效模式',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }}];
var eta_Field = [
    /*{field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'analyzeStage',title:'分析阶段',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }},
    {field:'safetyProtect',title:'安全防护',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }}

];
var fta_Field = [
    /*{field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'analyzeProject',title:'分析项目',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }}
];
var hazop_Field = [
   /* {field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'node',title:'节点',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }},
    {field:'deviation',title:'偏差',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50
        }
    }}

];
var jha_Field = [
    /*{field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'jobStep',title:'作业步骤',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }}
];
var jsa_Field = [
    /*{field:'id',width:100,checkbox:true},*/
    //{field:'dutyUserId',width:100,hidden:true},
    {field:'jobStep',title:'作业步骤',width:300, editor:{type:'textbox',
        options:{
            multiline:true,
            required:'true',
            height:50

        }
    }}
];
/**
 * 查询部门树方法
 */
function queryDepartmentTree(){
    $.ajax({
        url:ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data:{parentId : 0},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#dept').combotree(
                {
                    data:result,
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        newData.push(data[0]);
                        return newData;
                    }
                }
            );
            /*$("#dutyDept").combotree({
                data:result,
                loadFilter:function(data){
                    var newData = new Array();
                    newData.push({id:"",text:'请选择'});
                    newData.push(data[0]);
                    return newData;
                }
            });
            //主管部门
            $("#competentDept").combotree({
                data:result,
                loadFilter:function(data){
                    var newData = new Array();
                    newData.push({id:"",text:'请选择'});
                    newData.push(data[0]);
                    return newData;
                }
            });*/
        }
    });
}
/**
 * 查询风险区域列表
 */
function queryRegionList(){
    $.ajax({
        url:ROOT_PATH + '/risk/region/queryComboboxList.shtml',//提交地址
        data:{},
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#region').combobox(
                {
                    data:result,
                    valueField:'id',
                    textField:'text',
                    //limitToList:'true',
                    /*loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        for(var i=0;i<data.length;i++){
                            newData.push(data[i])
                        }
                        return newData;
                    },*/
                    //hasDownArrow:false,//隐藏倒三角
                    onSelect:function (param) {
                        $('#regionId').val(param.id);
                        queryRegionPointList(param.id);
                    },
                    onChange:function(newVal,oldVal){
                        //区分选中还是手动输入
                        if(newVal.length !=32){
                            $('#regionId').val('');
                        }
                    }
                }
            );

        }
    });
}
/**
 * 查询风险点列表
 */
function queryRegionPointList(regionId){
    $.ajax({
        url:ROOT_PATH + '/risk/region/point/queryComboboxList.shtml?regionId='+regionId,//提交地址
        data:{},
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#regionPoint').combobox(
                {
                    data:result,
                    valueField:'id',
                    textField:'text',
                    /*loadFilter:function(data){
                     var newData = new Array();
                     newData.push({id:"",text:'请选择'});
                     for(var i=0;i<data.length;i++){
                     newData.push(data[i])
                     }
                     return newData;
                     },*/
                    onSelect:function (param) {
                        $('#regionPointId').val(param.id);
                    },
                    onChange:function(newVal,oldVal){
                        //区分选中还是手动输入
                        if(newVal.length !=32){
                            $('#regionPointId').val('');
                        }
                    }
                }
            );

        }
    });
}
/**
 * 人员选择
 */
var add_contractorInfo_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=1',
        callBack:function(data){//窗口关闭后的回调函数
            //$('#listGrid').datagrid("reload");
            if(selectUserId==""||selectUserId==null){
                var dutyUserED= datagrid.datagrid('getEditor', {index:editRow,field:'dutyUserName'});
                var dutyUserIdED= datagrid.datagrid('getEditor', {index:editRow,field:'dutyUserId'});
                $(dutyUserED.target).textbox("setValue",data[0].name)
                $(dutyUserIdED.target).textbox("setValue",data[0].id)
            }else{//给正常文本框赋值
                /*$('#'+selectUserId).tagbox({
                    tagStyler: function(value){
                        if (value == 3){
                            return 'background:#ffd7d7;color:#c65353';
                        } else if (value == 4){
                            return 'background:#b8eecf;color:#45872c';
                        }
                    }
                });*/
                //设置data
                $('#'+selectUserId).tagbox({
                    data:data,
                    valueField:'id',
                    textField:'realName',
                    onBeforeRemoveTag:function(value){
                        //alert(value);
                        var val = $('#recogniseUsers').tagbox("getValues");
                        if(val.length<=1){
                            return false;
                        }
                    }
                });
                //选中所有的data
                for(i=0;i<data.length;i++){
                    $('#'+selectUserId).tagbox("select",data[i].id);
                }

                selectUserId = "";
            }

        }
    });
};
var add_jobProject_func=function(){
    WindowManager.openLayer({
        type: 2,
        title: '选择项目',
        area: ['800px', '300px'],
        content: ROOT_PATH + '/threeSimultaneities/projectInfo/projectQueryList.shtml',
        callBack: function(data){
            //alert();
            $("#jobProjectId").val(data[0].id);
            $("#jobProject").textbox("setValue",data[0].name);
            //("#jobProject").textbox("setText",data[0].name);
        }
    });
}
/**
 * 查询数据字典列表的方法
 * @param id
 * @param code
 */
function queryDictionaryList(id,code){
    $.ajax({
        url:ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',//提交地址
        data:{code : code},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#'+id).combobox(
                {
                    data:result,
                    valueField:'id',
                    textField:'text',
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        for(var i=0;i<data.length;i++){
                            newData.push(data[i])
                        }
                        return newData;
                    }
                }
            );

        }
    });
}
/**
 * 查询评价方法数据字典
 * @param id
 * @param code
 */
function queryMethodTypeList(id,code){
    $.ajax({
        url:ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',//提交地址
        data:{code : code},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            var data = [];
            //判断是否是首次进入加载
            if(!methodTypeData){
                var methodTypeId=$("#methodTypeId").val();
                //alert(methodTypeData);
                for(i=0;i<result.length;i++){
                    if(result[i].id == methodTypeId){
                        var tableField = eval(result[i].data2+"_Field").concat(base_Field);
                        tableOptions.columns = [tableField];
                        datagrid = $("#detailList").datagrid(tableOptions);
                    }
                    if(result[i].data1 == recogniseType || result[i].data1== 2){
                        data.push(result[i]);
                    }
                }
                methodTypeData =1;
            }else{
                for(i=0;i<result.length;i++){
                    if(result[i].data1 == recogniseType || result[i].data1== 2){
                        data.push(result[i]);
                    }
                }
            }
            $('#'+id).combobox(
                {
                    data:data,
                    valueField:'id',
                    textField:'text',
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        for(var i=0;i<data.length;i++){
                            newData.push(data[i])
                        }
                        return newData;
                    },
                    onChange:function(newVal,oldVal){
                        if(datagrid){
                            if($("#detailForm").form("validate")){
                                saveTableRow();
                            }else{
                                datagrid.datagrid('deleteRow', editRow);
                                editRow=undefined;
                            }
                        }
                        if(newVal){
                            //$("#detailListDiv").children().show();
                            for(i=0;i<data.length;i++){
                                if(data[i].id==newVal){
                                    var tableField = eval(data[i].data2+"_Field").concat(base_Field);
                                    tableOptions.columns = [tableField];
                                    datagrid = $("#detailList").datagrid(tableOptions);
                                }
                            }
                        }else{
                           $("#detailListDiv").children().hide();
                        }

                    }
                }
            );

        }
    });
}
/**
 * 选择风险信息弹出框方法
 */
var add_riskLevelInfo_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择风险矩阵信息',
        area: ['60%', '70%'],
        content: ROOT_PATH + '/risk/matrix/toMatrixPage.shtml',
        callBack:function(data){//窗口关闭后的回调函数
            var riskGradeED= datagrid.datagrid('getEditor', {index:editRow,field:'riskGrade'});
            var riskGradeIdED= datagrid.datagrid('getEditor', {index:editRow,field:'riskGradeId'});
            $(riskGradeED.target).textbox("setValue",data.riskMax)
            //$(riskGradeIdED.target).textbox("setValue",data.id)


        }
    });
};
/**
 * 查询风险类别
 */
function queryRiskType(){
    $.ajax({
        url:ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',//提交地址
        data:{code :CONSTANT.DictionaryTypeDefConstants.RISK_TYPE },//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            var riskTypeIdED= datagrid.datagrid('getEditor', {index:editRow,field:'riskTypeId'});
            var riskTypeNameED= datagrid.datagrid('getEditor', {index:editRow,field:'riskTypeName'});

            //var dutyUserIdED= datagrid.datagrid('getEditor', {index:editRow,field:'dutyUserId'});
            //$(progressNodeNameED.target).textbox("setValue",data[0].name)
            //$(dutyUserIdED.target).textbox("setValue",data[0].id)
            $(riskTypeIdED.target).combotree(
                {
                    data:result,
                    valueField:'id',
                    textField:'text',
                    editable:false,
                    required:true,
                    validType:'validSelect',
                    width:100,
                    panelWidth:150,
                    multiple:'true',
                    //value:,
                    /*onSelect:function(r){
                        console.log(r);
                        $(riskTypeNameED.target).textbox('setValue',r.text);
                    },*/
                    /*onChange:function(n,o){
                        $(riskTypeNameED.target).textbox('setValue',n);
                    },*/
                    onHidePanel:function(){
                        $(riskTypeNameED.target).textbox('setValue',$(this).combotree('getText'));
                        //$(riskTypeIdED.target).combobox('setValue',$(this).val());
                       // $(riskTypeIdED.target).combobox('setText',$(this).combotree('getText'));
                    },
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        for(var i=0;i<data.length;i++){
                            newData.push(data[i])
                        }
                        return newData;
                    },
                    onLoadSuccess:function(){
                        //设置初始值
                        //$(riskTypeIdED.target).combotree("setValues",datagrid.datagrid('getRows')[editRow].riskTypeId);
                        var val = datagrid.datagrid('getRows')[editRow].riskTypeId;
                        if(val){
                            $(riskTypeIdED.target).combotree("setValues",val);
                        }

                    }
                }
            );


        }
    });
}
/*==============================================================================*/
/**
 * 添加编辑行
 */
function appendTableRow() {//添加列表的操作按钮添加，修改，删除等
    //添加时先判断是否有开启编辑的行，如果有则把开户编辑的那行结束编辑
    if (editRow != undefined) {
        datagrid.datagrid("endEdit", editRow);
    }
    //添加时如果没有正在编辑的行，则在datagrid的第一行插入一行
    if (editRow == undefined) {
        datagrid.datagrid("insertRow", {
            index: 0, // index start with 0
            row: {

            }
        });
        //将新插入的那一行开启编辑状态
        datagrid.datagrid("beginEdit", 0);
        //给当前编辑的行赋值
        editRow = 0;
    }
    //加载风险类型下拉列表
    queryRiskType();
}

/**
 * 删除行
 */
function deleteTableRow () {
    //删除时先获取选择行
    var rows = datagrid.datagrid("getSelections");
    //选择要删除的行
    if (rows.length > 0) {
        var index = layer.confirm("确定要删除吗？",{btn:["确定","取消"]},function(){
            var ids = [];
            /*for (var i = 0; i < rows.length; i++) {
             ids.push(rows[i].ID);
             }*/
            var row= datagrid.datagrid("getSelected");
            var selectedIndex =  datagrid.datagrid('getRowIndex',row);
            datagrid.datagrid('deleteRow', selectedIndex);
            editRow=undefined;
            //将选择到的行存入数组并用,分隔转换成字符串，
            //本例只是前台操作没有与数据库进行交互所以此处只是弹出要传入后台的id
            //alert(ids.join(','));
            layer.close(index);
        });
    }else {
        layer.alert("请选择删除行！");
    }
}

/**
 * 保存行数据
 */
function saveTableRow () {
    //保存时结束当前编辑的行，自动触发onAfterEdit事件如果要与后台交互可将数据通过Ajax提交后台
    datagrid.datagrid("endEdit", editRow);
}

/**
 * 编辑行数据
 */
function editTableRow() {
    //修改时要获取选择到的行
    var rows = datagrid.datagrid("getSelections");
    //如果只选择了一行则可以进行修改，否则不操作
    if (rows.length == 1) {
        //修改之前先关闭已经开启的编辑行，当调用endEdit该方法时会触发onAfterEdit事件
        if (editRow != undefined) {
            datagrid.datagrid("endEdit", editRow);
        }
        //当无编辑行时
        if (editRow == undefined) {
            //获取到当前选择行的下标
            var index = datagrid.datagrid("getRowIndex", rows[0]);
            //开启编辑
            datagrid.datagrid("beginEdit", index);
            //把当前开启编辑的行赋值给全局变量editRow
            editRow = index;
            //当开启了当前选择行的编辑状态之后，
            //应该取消当前列表的所有选择行，要不然双击之后无法再选择其他行进行编辑
            datagrid.datagrid("unselectAll");
        }
    }
    //加载风险类型下拉列表
    queryRiskType();

}
/**
 * 取消编辑行
 */
function rejectTableRow () {
    var index =  layer.confirm("确定撤销将删除所有的编辑数据！",{btn:['确定','取消']},function(){
        //取消当前编辑行把当前编辑行罢undefined回滚改变的数据,取消选择的行
        editRow = undefined;
        datagrid.datagrid("rejectChanges");
        datagrid.datagrid("unselectAll");
        layer.close(index);
    });

}
/**
 * 提交表格数据
 */
function getDetailData(){
    //保存表格编辑数据
    saveTableRow();
    //获取编辑表格数据
    var rows= datagrid.datagrid("getData").rows;
    return JSON.stringify(rows);
}